package com.codestudy.service.impl;

import cn.undraw.util.result.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codestudy.common.LoginUtil;
import com.codestudy.dao.CommentLikeDao;
import com.codestudy.dto.LikedDTO;
import com.codestudy.entity.Comment;
import com.codestudy.entity.CommentLike;
import com.codestudy.service.CommentLikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author readpage
 * @since 2023-02-03 16:15
 */
@Slf4j
@Service
public class CommentLikeServiceImpl extends ServiceImpl<CommentLikeDao, CommentLike> implements CommentLikeService {
    @Resource
    private CommentLikeDao commentLikeDao;

    @Override
    public boolean removeBatchByCid(List<Integer> cList) {
        return commentLikeDao.deleteBatchByCid(cList) > 0;
    }


    /**
     * 获取mysql点赞状态
     */
    private CommentLike getByLikedDTO(LikedDTO likedDTO) {
        // 获取mysql中的点赞状态
        return commentLikeDao.selectOne(
                new QueryWrapper<CommentLike>()
                        .eq("uid", likedDTO.getUid())
                        .eq("comment_id", likedDTO.getCommentId())
        );
    }

    @Override
    public R cidListByUid(Integer uid) {
        List<CommentLike> commentList = commentLikeDao.selectByCID(uid);
        return R.ok(commentList);
    }

    /**
     * 点赞评论
     */
    @Override
    public R liked(Integer commentId) {
        // 查询用户是否点赞
        CommentLike commentLike = new CommentLike();
        commentLike.setUid(LoginUtil.getCurrentId());
        commentLike.setCommentId(commentId);

        List<Comment> commentList = commentLikeDao.selectByU(commentLike);
        if (CollectionUtils.isEmpty(commentList)) {
            // 没数据
            CommentLike cl = new CommentLike();
            cl.setCommentId(commentId);
            cl.setCreateTime(LocalDateTime.now());
            cl.setUid(LoginUtil.getCurrentId());
            cl.setUpdateTime(LocalDateTime.now());
            commentLikeDao.commentLikeInsert(cl);

            log.info("点赞ID为：{}", cl.getUid());
            return R.ok("点赞成功");
        } else {
            // 有数据
            // 取消点赞
            commentLikeDao.commentLikeDelete(commentId);
            return R.ok("取消点赞");
        }
    }


}
